<template>
  <div class="column-module">
    <div class="section-container">
      <div class="section-title">
        栏目模板
      </div>
      <div class="section-description">
        <i class="iconfont">&#xe60e;</i>
        <p>页面模板：用于定义栏目列表页的展示样式和布局。详情模板：用于定义栏目内容详情页的展示样式和布局。
        <br />提示：本页面仅提供代码形式修改模板，请确保您具备相关技术能力。如需可视化拖拽设计功能，请联系技术支持。</p>
      </div>
      <el-tabs v-model="activeType" @tab-change="changeTab">
        <el-tab-pane v-for="(item, index) in typeList" :key="index" :label="item.label" :name="item.value"></el-tab-pane>
      </el-tabs>
      <div class="section-actions">
        <div class="actions-left">
          <SearchCmp v-if="searchCmpArray.length" ref="searchCmpRef" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getTableData" />
        </div>
      </div>
      <RuifoxTable :loading="tableLoading" :default-index="false" :default-checkbox="false" v-model:tableData="tableData" v-model:fieldList="fieldList">
        <!-- 使用情况 -->
        <template #useCategoryName="{ element }">
          <span>{{ getUseText(element) }}</span>
        </template>
        <!-- 多选 -->
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
          </div>
        </template>
        <!-- 操作列 -->
        <template #options="{ element }">
          <div class="button-box">
            <el-button v-permission="['build:module:column:edit']" link type="primary" @click="handleEditByCode(element)">修改</el-button>
            <!-- <el-dropdown v-permission="['build:module:column:delete']" trigger="click">
              <i class="iconfont">&#xe771;</i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <span @click="handleDelete(element)">删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
          </div>
        </template>
      </RuifoxTable>

      <div class="footer">
        <PaginationView
          :total="queryData.total"
          :pageSize="queryData.pageSize"
          :currentPage="queryData.currentPage"
          :allChoose="isAllChooseBtn"
          :pageChoose="isPageChooseBtn"
          :checkedNum="checkedNum"
          :canChoose="false"
          @changeSize="handleSizeChange"
          @currentChange="handleCurrentChange"
          @changePageChoose="handlePageChoose"
          @changeAllChoose="handleAllChoose"
          @invertChoose="handleInvertChoose"
          @refreshList="getTableData"
          @cancelChoose="handleResetPagination"
        />
      </div>
    </div>
    <el-drawer v-model="drawerVisible" :title="dataForm.id ? '修改模板' : '添加模板'" direction="rtl" custom-class="module-drawer" size="50%" @close="resetForm">
      <el-form ref="dataFormRef" :rules="dataFormRules" :model="dataForm" label-width="100px" label-position="right">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="引用组件" prop="importIds">
          <el-select v-model="dataForm.importIds" placeholder="请选择引用组件" multiple clearable disabled style="width: 100%">
            <el-option-group v-for="(group, index) in templateGroup" :key="index" :label="group.label">
              <el-option v-for="item in group.options" :key="item.id" :label="item.label" :value="item.value" />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <div style="width: 100%">
            <el-tabs v-model="activeName" type="card">
              <el-tab-pane label="HTML" name="html"></el-tab-pane>
              <el-tab-pane label="component-list" name="javascript"></el-tab-pane>
              <el-tab-pane label="properties" name="json"></el-tab-pane>
            </el-tabs>
            <div class="editor-box">
              <CodeEditor v-model="currentContent" :language="activeName" />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :loading="optionLoading" @click="submitDataForm">确认</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectTemplatePage, insertTemplate, updateTemplate, selectTemplateList, deleteTemplate, batchDeleteTemplate } from '@/api/template'
import { useStore } from 'vuex'
import { tableList as mixTable } from '@ruifox-cms/utils'

const store = useStore()
const activeType = ref(2)
const typeList = reactive([
  { label: '页面模板', value: 2 },
  { label: '详情模板', value: 3 }
])
const changeTab = tab => {
  queryData.type = tab
  searchCmpRef.value.clearForm(queryData)
  searchCmpRef.value.showTags()
  handleResetPagination()
  getTableData()
}
// 获取模板
const searchCmpRef = ref(null)
const searchCmpArray = ref([
  { label: '模板名称', key: 'name' },
  { label: '模板路径', key: 'path' }
])
// 使用 mixTable mixin
const {
  tableLoading,
  checkedList,
  isAllChooseBtn,
  isPageChooseBtn,
  isAllSearch,
  checkedNum,
  queryData,
  tableData,
  getTableData,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectTemplatePage
})
const defaultQuery = {
  siteId: store.state.site.currentSite.id,
  total: 0,
  currentPage: 1,
  pageSize: 10,
  type: 2,
  name: '',
  macro: ''
}
Object.assign(queryData, defaultQuery)
getTableData()
// 定义表格列配置
const fieldList = ref([
  {
    title: '模板ID',
    name: 'id',
    width: 80
  },
  {
    title: '模板名称',
    name: 'name'
  },
  {
    title: '使用情况',
    name: 'useCategoryName'
  },
  {
    title: '模板路径',
    name: 'path'
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    name: 'options'
  }
])
// 获取所有模板，创建模板时，选择引用需要
const templateGroup = ref([
  { label: '组件', options: [] },
  { label: '指令', options: [] },
  { label: 'CSS', options: [] },
  { label: 'JS', options: [] }
])
const _getAllTemplateList = async () => {
  let res = await selectTemplateList()
  res.data.forEach(item => {
    if (item.type === 0) {
      templateGroup.value[0].options.push({ label: item.name, value: item.id })
    }
    if (item.type === 1) {
      templateGroup.value[1].options.push({ label: item.name, value: item.id })
    }
    if (item.type === 10) {
      templateGroup.value[2].options.push({ label: item.name, value: item.id })
    }
    if (item.type === 11) {
      templateGroup.value[3].options.push({ label: item.name, value: item.id })
    }
  })
}
_getAllTemplateList()

// 模板引用描述
const getUseText = (data) => {
  if (data.useCategoryName.length === 0) {
    return '未被栏目使用'
  }
  let columnName = data.useCategoryName.slice(0, 2).map(item => item.name).join('、')
  return `${columnName}等${data.useCategoryName.length}个栏目使用`
}

// 添加模板
const drawerVisible = ref(false)
const activeName = ref('html')
const optionLoading = ref(false)
const dataFormRef = ref()
const dataFormRules = reactive({
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }]
})
const defaultDataForm = reactive({
  name: '',
  content: '',
  type: 2,
  path: '',
  importIds: [],
  isBase: false
})
let dataForm = ref(Object.assign({}, defaultDataForm))
// 代码修改模板
const handleEditByCode = data => {
  Object.assign(dataForm.value, data)
  activeName.value = 'html'
  currentContent.value = structuredClone(dataForm.value.content)
  dataForm.value.componentList = JSON.stringify(dataForm.value.componentList, null, 2).replace(/\n/g, '\r\n')
  dataForm.value.properties = JSON.stringify(dataForm.value.properties, null, 2).replace(/\n/g, '\r\n')
  drawerVisible.value = true
}
const submitDataForm = async () => {
  if (!dataFormRef.value) return
  await dataFormRef.value.validate(async valid => {
    if (valid) {
      optionLoading.value = true
      let res
      if (!dataForm.value.id) {
        res = await insertTemplate(dataForm.value)
      } else {
        delete dataForm.value.path
        res = await updateTemplate(dataForm.value)
      }
      optionLoading.value = false
      if (res.code === 20000) {
        drawerVisible.value = false
        ElMessage({
          showClose: true,
          message: '操作成功',
          type: 'success'
        })
        getTableData()
      }
    }
  })
}
// // 删除模板
// const handleDelete = data => {
//   ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选模板？</p><span style="font-size: 14px;color: #FF5240;">删除后模板将被移除</span></div>', '删除确认', {
//     dangerouslyUseHTMLString: true,
//     confirmButtonText: '确认',
//     cancelButtonText: '取消'
//   }).then(() => {
//     deleteTemplate({ id: data.id }).then(() => {
//       //更新节点
//       getTableData()
//       ElMessage({
//         showClose: true,
//         message: '删除成功',
//         type: 'success'
//       })
//     })
//   })
// }

// 批量删除
// const batchOptions = ref([{ name: '删除', value: 'delete', icon: '&#xe74b;' }])
// const handleBatchDelete = () => {
//   ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否批量删除所选模板？</p><span style="font-size: 14px;color: #FF5240;">删除后模板将被移除</span></div>', '删除确认', {
//     dangerouslyUseHTMLString: true,
//     confirmButtonText: '确认',
//     cancelButtonText: '取消'
//   }).then(() => {
//     batchDeleteTemplate({ ids: checkedList.value, isAllChoose: isAllSearch.value }).then(() => {
//       //更新节点
//       handleResetPagination()
//       getTableData()
//       ElMessage({
//         showClose: true,
//         message: '删除成功',
//         type: 'success'
//       })
//     })
//   })
// }
const resetForm = () => {
  dataFormRef.value.resetFields()
  dataForm.value = Object.assign({}, defaultDataForm)
  optionLoading.value = false
}

const currentContent = ref('')
watch(currentContent, val => {
  if (activeName.value === 'html') {
    dataForm.value.content = val
  } else if (activeName.value === 'javascript') {
    dataForm.value.componentList = val
  } else if (activeName.value === 'json') {
    dataForm.value.properties = val
  }
})

watch(activeName, val => {
  if (val === 'html') {
    currentContent.value = structuredClone(dataForm.value.content)
  } else if (val === 'javascript') {
    currentContent.value = structuredClone(dataForm.value.componentList)
  } else if (val === 'json') {
    currentContent.value = structuredClone(dataForm.value.properties)
  }
})
</script>

<style scoped lang="scss">
.button-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  i {
    margin-left: 10px;
    color: $mainColor;
    cursor: pointer;
  }
}

::v-deep .module-drawer {
  .editor-box {
    width: 100%;
    height: 600px;
    margin-top: -16px;
    border: 1px solid var(--el-border-color-light);
    border-bottom-right-radius: 4px;
    border-bottom-left-radius: 4px;

    .code-textarea {
      width: 100%;
      height: 100%;
      padding: 10px;
      border: none;
      resize: none;
      font-family: monospace;
      font-size: 14px;
      line-height: 1.5;
      outline: none;
    }
  }
  .thumb-box {
    .thumb-box-img {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 10px;
      width: 280px;
      height: 120px;
      border: 1px dashed $borderColor;
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
  }
}

</style>
